<?php

class AuthController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
        $this->view->baseUrl = $this->_request->getBaseUrl();
        $this->view->cliente = Zend_Auth::getInstance()->getIdentity();
    }

    public function indexAction()
    {
        /* Como no voy a usar esta acción */
        /* redirigimos a la ruta por defecto */
        /* cualquier intento de navegar al */
        /* directorio auth/index */
        $this->_redirect('/');
    }

    public function loginAction()
    {
        $this->view->titulo = "Acceso";
        // si quiero hacer login y ya estoy logueado
        $auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity()) {
            return $this->_redirect('/');
        }
        
        $form = new Application_Form_Login();
        
        if( $this->getRequest()->isPost() ){
            
            if( $form->isValid( $this->_getAllParams() )) {
                // setup Zend_Auth adapter for a database table
                Zend_Loader::loadClass('Zend_Auth_Adapter_DbTable');
                $dbAdapter = Zend_Registry::get('dbAdapter');
                $authAdapter = new Zend_Auth_Adapter_DbTable(
                    $dbAdapter,
                    'usuarios',
                    'usuario',
                    'clave'
                );
                
                $authAdapter
                    ->setIdentity($form->getValue('usuario'))
                    ->setCredential(sha1($form->getValue('clave')));
                
                $auth = Zend_Auth::getInstance();
                $result = $auth->authenticate($authAdapter);
                
                if ($result->isValid()) {
                    // success: store database row to auth's storage
                    // system. (Not the password though!)
                    $data = $authAdapter->getResultRowObject(null,'clave');
                    $auth->getStorage()->write($data);
                    $this->_redirect('/');
                } else {
                    // failure: clear database row from session
                    $this->view->error = TRUE;
                    $this->view->mensaje = "Datos incorrectos";
                }
                
            }
        }
        $this->view->form = $form;
     
    }   

    public function logoutAction()
    {
        // No necesita un archivo .phtml porque redirijo al inicio
        Zend_Auth::getInstance()->clearIdentity();
        $this->_redirect('/');
    }


}



